import { Component, OnInit, ChangeDetectorRef, ViewChild } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
import { MdPaginator, MdSnackBar, MD_DIALOG_DATA } from "@angular/material";
import { ApiServiceService } from '../api.service'
import { MdDialog, MdDialogRef } from '@angular/material';
import { DialogService, DeleteManaConfirm } from "../service/dialog.service";

@Component({
  selector: 'app-play-system',
  templateUrl: './play-system.component.html',
  styleUrls: ['./play-system.component.css']
})
export class PlaySystemComponent implements OnInit {

  constructor(private apiService: ApiServiceService,
    private changeDetectorRef: ChangeDetectorRef,
    private dialogService: DialogService,
    public snackBar: MdSnackBar,
    public dialog: MdDialog) {
  }

  displayedColumns = ['deleteFlag', /*'no',*/ 'EBRID', 'EBRName', 'Longitude', 'Latitude', 'Square', 'AreaCode', 'Population', 'LanguageCode', 'URL', 'operation'];
  soundSourceDatabase = new SoundSourceDatabase();
  dataSource: SoundSourceDataSource | null;
  allSelectedFlag: boolean;

  @ViewChild(MdPaginator) paginator: MdPaginator;

  playSysInfo: Object = {};
  playSysList: Array<any>;
  playSysHead: Array<any>;
  noneText: string = '';

  ngOnInit() {
    this.dataSource = new SoundSourceDataSource(this.soundSourceDatabase, this.paginator);
    this.changeDetectorRef.detectChanges();
    this.allSelectedFlag = false;
    this.apiService.getAllInfo('EBRBS').subscribe(res => {
      if (res.success) {
        this.playSysInfo = res.data;
        this.playSysHead = res.data.header;
        this.playSysList = res.data.content;


        this.soundSourceDatabase.refreshData(this.playSysList);

      } else {
        this.dialogService.openSnackBar("初始化失败，请重试！", "");
      }
      err => {
        this.apiService.doError(err);
        this.noneText = "服务器故障，请刷新"
      }

    })

  }

  refresh() {
    this.ngOnInit();
  }


  add() {
    let stationitem = { EBRID: '', EBRName: '', URL: '', Longitude: '', Latitude: '', Square: '', AreaCode: '', Population: '', LanguageCode: '', isEdit: true, isNew: true }
    this.playSysList.push(stationitem)
    this.soundSourceDatabase.refreshData(this.playSysList);
  }

  edit(row) {
    row.isEdit = true;
  }

  delete(row) {
    // debugger;
    this.dialogService.openDeleteConfirm()
      .afterClosed()
      .subscribe(res => {
        if (res) {
          this.apiService.deleteEom("EBRBS", [row._id]).subscribe(res => {
            if (res.success) {
              this.openSnackBar("删除成功。", "");
              row.isEdit = false;
              this.refresh();
            } else {
              this.openSnackBar(res.error, "");
            }
          })
        }
      })

  }

  reportAll() {
    let data = [];
    this.playSysList.map(item => {
      if (item.isChecked) {
        data.push(item.EBRID);
      }
    })


    this.apiService.reportEom("EBRBS", [data]).subscribe(res => {
      console.log(res);
      setTimeout(() => {
        if (res.success) {
          this.openSnackBar("上报成功。", "");
        } else {
          this.openSnackBar("上报失败,请稍后再试。", "");
        }

      }, 2000);

    });
  }

  ////['deleteFlag', /*'no',*/ 'EBRID', 'EBRName','Longitude','Latitude','Square','AreaCode','Population','LanguageCode', 'URL', 'operation'];
  finish(row) {
    if (row.isNew) {
      if (row.EBRID != "" && row.EBRName != "" && row.URL != "" && row.Longitude != "" && row.Latitude != "" && row.Square != "" && row.AreaCode != "" && row.Population != "" && row.LanguageCode != "") {
        this.apiService.addEom("EBRBS", row).subscribe(res => {
          console.log(res);
          if (res.success) {
            this.openSnackBar("添加成功。", "");
            row.isEdit = false;
            row.isNew = false;
          } else {
            this.openSnackBar("添加失败", "");
          }
        })
      } else {
        this.openSnackBar("文本不能为空", "");
      }
    } else {
      this.apiService.updateEom("EBRBS", row).subscribe(res => {
        console.log(res);
        if (res.success) {
          this.openSnackBar("修改成功。", "");
          row.isEdit = false;
        } else {
          this.openSnackBar("res.err。", "");
        }
      })
    }

  }


  report(row) {
    let formData = new FormData();
    formData.append("EBMID", row.EBMID);
    this.apiService.reportInfo(formData)
      .subscribe(res => {
        setTimeout(() => {
          if (res.success) {
            this.openSnackBar("上报成功。", "");
          } else {
            this.openSnackBar("上报失败,请稍后再试。", "");
          }
        }, 3000)
      });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 3000,
    });
  }
}


const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];



export interface SoundSourceData {
  deleteFlag: boolean;
  // no:string;
  EBRID: string;
  EBRName: string;
  URL: string;
  Longitude: string;
  Latitude: string;
  Square: string,
  AreaCode: string,
  Population: string,
  LanguageCode: string
  // status:string;
  operation?: any
  isChecked: boolean,
}

export class SoundSourceDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<SoundSourceData[]> = new BehaviorSubject<SoundSourceData[]>([]);

  get data(): SoundSourceData[] {
    return this.dataChange.value;
  }


  constructor() {
    // Fill up the database with 100 users.
    var _a: SoundSourceData[] = [
      // {
      //   "deleteFlag": false,
      //   "no": "1",
      //   "acaption": "网络节目源1",
      //   "acontent": "7001",
      //   "uid": "admin",
      //   "isChecked": false
      //
      // }
    ];
    this.dataChange.next(_a);


    // for (var i = 0; i < 100; i++) {
    //   this.addUser();
    // }
  }


  refreshData(array) {
    array.forEach(function (item, index) {
      item.no = index + 1;
    })
    this.dataChange.next(<SoundSourceData[]>array);
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }



  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      deleteFlag: false,
      // no: (this.data.length + 1).toString(),
      EBRID: name,
      EBRName: Math.round(Math.random() * 100).toString(),
      URL: COLORS[Math.round(Math.random() * (COLORS.length - 1))],
      Longitude: (this.data.length + 1).toString(),
      Latitude: (this.data.length + 1).toString(),
      Square: (this.data.length + 1).toString(),
      AreaCode: (this.data.length + 1).toString(),
      Population: (this.data.length + 1).toString(),
      LanguageCode: (this.data.length + 1).toString(),
      operation: (this.data.length + 1).toString(),
      isChecked: false,
    };
  }
}

export class SoundSourceDataSource extends DataSource<any> {
  constructor(private _soundSourceDatabase: SoundSourceDatabase, private _paginator: MdPaginator) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<SoundSourceData[]> {
    const displayDataChanges = [
      this._soundSourceDatabase.dataChange,
      this._paginator.page,
    ];
    return Observable.merge(...displayDataChanges).map(() => {
      const data = this._soundSourceDatabase.data.slice();

      // Grab the page's slice of data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    });

  }

  disconnect() {
  }
}

